package com.example.campus.controller.user;

import com.example.campus.result.Result;
import com.example.campus.utils.MinIOUtil;
import com.example.campus.utils.constant.MessageConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/user/upload")
@Slf4j
@Api(tags = "图片上传相关接口")
public class UploadController {
    @Autowired
    private MinIOUtil minIOUtil;

    private static final String AVATAR_FOLDER = "avatar";

    private static final String INFO_FOLDER = "info";

    @PostMapping("/info")
    @ApiOperation("失物/拾物信息图片上传（可多张）")
    public Result<List<String>> upload(@RequestParam("files") MultipartFile[] files) {
        List<String> imageUrls = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                String originalFilename = file.getOriginalFilename();
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String objectName = UUID.randomUUID().toString() + extension;

                String imageUrl = minIOUtil.upload(file.getBytes(), objectName, INFO_FOLDER);
                imageUrls.add(imageUrl);
                log.info("文件路径:{}", imageUrl);
            }
            return Result.success(imageUrls);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

    @PostMapping("/avatar")
    @ApiOperation("用户头像图片上传")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {
        try {
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String objectName = UUID.randomUUID().toString() + extension;

            String imageUrl = minIOUtil.upload(file.getBytes(), objectName, AVATAR_FOLDER);
            log.info("文件路径:{}", imageUrl);
            return Result.success(imageUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
